package com.tech.platform.cms.authz.sso.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.tech.platform.cms.authz.sso.config.SsoYmlConfig;
import com.tech.platform.cms.authz.sso.service.JwtTokenService;
import com.tech.platform.cms.common.constant.Constant;
import com.tech.platform.cms.common.model.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt 过滤器
 * header 中不存在 HGC,或者HGC过期,则重定向到登陆页面
 */
@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenService jwtTokenService;

    @Autowired
    private SsoYmlConfig ssoYmlConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain chain) throws IOException, ServletException {
        //判断白名单列表,不在白名单则执行过滤
        if(CollUtil.isNotEmpty(ssoYmlConfig.getWhiteListUrls())){
            for (String url : ssoYmlConfig.getWhiteListUrls()){
                if(new AntPathMatcher().match(url,httpServletRequest.getServletPath())){
                    chain.doFilter(httpServletRequest,httpServletResponse);
                    return;
                }
            }
        }
        //1.首先获取Hgt token 如果不为空,验证token状态
        //2.如果hgt为空,获取htc,如果存在,换取hgt token
        //3.如果hgc为空,跳转到登陆验证,进行登陆
        try {
            String hgtToken = httpServletRequest.getHeader("Authorization");
            String clientId = httpServletRequest.getHeader("clientId");
            if (StrUtil.isNotBlank(hgtToken)) {
                //token 验证失败,直接跳转登陆
                if (!jwtTokenService.checkHgtToken(hgtToken, clientId)) {
                    CommonResult<String> result = new CommonResult<>(Constant.HGT_TOKEN_ERROR,"hgt token check error");
                    httpServletResponse.getWriter().write(JSONUtil.toJsonStr(result));
                    return;
                }

                //判断hgt token 是否过期
                if (jwtTokenService.isHgtTokenExpired(hgtToken, clientId)) {
                    CommonResult<String> result = new CommonResult<>(Constant.TOKEN_EXPIRE,"hgt token is expire");
                    httpServletResponse.getWriter().write(JSONUtil.toJsonStr(result));
                    return;
                }
            } else {
                String hgcToKen = httpServletRequest.getHeader("hgcToken");
                //如果HGC token不存在,跳转到登陆页面
                if (StrUtil.isBlank(hgcToKen)) {
                    CommonResult<String> result = new CommonResult<>(Constant.HGC_TOKEN_ERROR,"hgc token is null");
                    httpServletResponse.getWriter().write(JSONUtil.toJsonStr(result));
                    return;
                }

                if (jwtTokenService.isHgcTokenExpire(hgcToKen)) {
                    CommonResult<String> result = new CommonResult<>(Constant.TOKEN_EXPIRE,"hgc token is expire");
                    httpServletResponse.getWriter().write(JSONUtil.toJsonStr(result));
                    return;
                }

                //验证hgc token,查看是否被串改
                if (!jwtTokenService.checkHgcToken(hgcToKen)) {
                    CommonResult<String> result = new CommonResult<>(Constant.HGC_TOKEN_ERROR,"hgc token check error");
                    httpServletResponse.getWriter().write(JSONUtil.toJsonStr(result));
                    return;
                }
            }
            chain.doFilter(httpServletRequest, httpServletResponse);
        }catch (Exception ex){
            CommonResult<String> result = new CommonResult<>(Constant.AUTHORIZATIONERROR,ex.getMessage());
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.getWriter().write(JSONUtil.toJsonStr(result));
            return;
        }
    }
}
